class SessionsController < ApplicationController
  filter_parameter_logging :password, :password_confirmation

  def new
  end

  def create
    logout_keeping_session!
    if params[:email].blank? or params[:password].blank?
      failed_signin
      @error = "你的email和密码不能为空，请填写完整再登录"
      return render :action => 'new'
    elsif params[:email] !~ /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
      failed_signin
      @error = "请输入正确的email地址"
      return render :action => 'new'
    end
    
    user = User.authenticate(params[:email], params[:password])
    if user
      unless user.active?
        redirect_to '/'
        flash.now[:error] = "您的帐号还未激活，请到您的注册邮件里点击激活帐号链接。"
      else
        self.current_user = user
        session[:user] = user
        user.update_attributes!(:last_login_time => Time.now)
        
        new_cookie_flag = (params[:remember_me] == "1")
        handle_remember_cookie! new_cookie_flag
        redirect_back_or_default('/')
        flash.now[:notice] = "登录成功。"
      end
    else
      #note_failed_signin
      failed_signin
      @error = "你的email和密码不符，请再试一次"
      render :action => 'new'
    end
  end

  def destroy
    logout_killing_session!
    flash[:notice] = "您已经登出。"
    redirect_back_or_default('/')
  end

protected
  # Track failed login attempts
  def note_failed_signin
    flash[:error] = "登录失败。"
    logger.warn "Failed login for '#{params[:email]}' from #{request.remote_ip} at #{Time.now.utc}"
  end
  
  def failed_signin
    @email       = params[:email]
    @remember_me = params[:remember_me]
  end
end
